package com.dex4d.async;

import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Toast;

import com.dex4d.R;
import com.dex4d.core.AppBaseActivity;
import com.dex4d.model.User;
import com.dex4d.model.WalletModel;
import com.dex4d.ui.demo.HomeActivity;
import com.dex4d.utils.EthWalletUtil;
import com.dex4d.utils.Log;

import java.util.List;

//创建钱包的异步线程

public  class KeyAsyncTask extends AsyncTask<Void, Void, Boolean> {

    private String password;
    private List<String> mBundleStrings;
    private Activity mContext;
    private boolean mBackup;

    public KeyAsyncTask(String pwd, List<String> bundleStrings,boolean backup,Activity context) {
        this.password = pwd;
        this.mBundleStrings = bundleStrings;
        this.mBackup = backup;
        this.mContext = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Boolean doInBackground(Void... voids) {
        WalletModel walletModel = EthWalletUtil.createEthWallet(mBundleStrings, password);
        return saveWallet(walletModel);
    }

    protected boolean saveWallet(WalletModel walletModel){
        try {
            User.getInstance().setAddress(walletModel.address);
            User.getInstance().setWalletName(walletModel.name);
            User.getInstance().setKeystore(walletModel.keystore);
            User.getInstance().setPassphrase(walletModel.passphrase);
            User.getInstance().setMnemonic(walletModel.mnemonicCodeList);
            User.getInstance().setBackup(mBackup);

            User.getInstance().save();

            //todo database update

        }catch (Exception e){
            Log.d("KeyAsyncTask","save wallet failure");
            return false;
        }
        return true;
    }

    @Override
    protected void onPostExecute(final Boolean flag) {
        if (!flag) {
            Toast.makeText(mContext, R.string.create_wallet_error, Toast.LENGTH_LONG).show();
            ((AppBaseActivity)mContext).dismissLoadingDialog();
            return;
        }else {
            HomeActivity.start(mContext);
            mContext.finish();
        }

    }

    public String formatMnemonic(List<String> mnemonicList){
        StringBuffer sb = new StringBuffer();
        for(String str:mnemonicList){
            sb.append(str).append(" ");
        }
        return sb.toString().trim();
    }
}
